<template>
  <div class="production">
    <!-- 按钮区域 -->
<!-- 按钮区域 -->
    <div class="btns">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <!-- 头部操作栏 -->
        <el-button class="toAddBtn" type="primary" @click="toAddProduct"
          >新增</el-button
        >
        <el-form-item>
          <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="正常" value="正常"></el-option>
            <el-option label="下架" value="下架"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="queryParams.productCategoryId"
            placeholder="请选择所属栏目"
            clearable
          >
            <el-option
              v-for="(item, index) in proCategories"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pageQueryProductions"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table :data="tabelData.list" size="small">
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column prop="name" label="产品名称"></el-table-column>
      <el-table-column label="图片">
        <template v-slot="scope">
          <el-popover placement="right" width="200" trigger="hover">
            <img :src="scope.row.photo" height="200px" />
            <img slot="reference" :src="scope.row.photo" alt="" height="50" />
          </el-popover> </template
      ></el-table-column>
      <el-table-column prop="price" label="价格"> </el-table-column>
      <el-table-column label="状态">
        <!-- scope.row表示作用域当前行 -->
        <template v-slot="scope">
          <el-tag type="success" v-if="scope.row.status == '正常'">{{
            scope.row.status
          }}</el-tag>
          <el-tag type="danger" v-else>{{ scope.row.status }}</el-tag>
        </template></el-table-column
      >
      <el-table-column prop="category.name" label="所属栏目"> </el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="text" @click="toEditHandler(scope.row)"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.status == '正常'"
            type="text"
            style="color: red"
            @click="upDownProductHandler(scope.row.id, $event)"
            >下架</el-button
          >
          <el-button
            v-else
            type="text"
            @click="upDownProductHandler(scope.row.id, $event)"
            >上架</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件区域 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tabelData.page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="tabelData.pageSize"
      layout="total, sizes, prev, pager, next"
      :total="tabelData.total"
    >
    </el-pagination>
    <!-- 模态框 -->
    <el-dialog :title="title" :visible.sync="visible">
      <el-form :model="product">
        <el-form-item label="产品名称" :label-width="formLabelWidth">
          <el-input
            v-model="product.name"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属栏目" :label-width="formLabelWidth">
          <el-select
            v-model="product.productCategoryId"
            placeholder="请选择所属栏目"
          >
            <el-option
              v-for="(item, index) in proCategories"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品价格" :label-width="formLabelWidth">
          <el-input
            v-model="product.price"
            placeholder="请输入产品价格"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品封面" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://81.69.24.232/pet/jz_upload.php"
            :on-success="handleUploadSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            v-model="product.description"
            placeholder="请输入产品描述信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSaveHandler">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from "@/utils/request";
import { mapState, mapActions } from "vuex";
import qs from "qs";
import _ from "lodash";
export default {
  data() {
    return {
      tabelData: {},
      queryParams: {
        page: 1,
        pageSize: 5,
      },
      visible: false,
      formLabelWidth: "80px",
      product: {},
      imageUrl: "",
      title: "",
      rules:{
        name:[{requied:true,message:'请输入产品的名称',trigger:"blur"}],
        productCategoryld:[{
          required:true,message:'请选择所属栏目',trigger:'change'
        }],
        price:[{
          required:true,message:'请输入产品的价格',trigger:'blur'
        }],
        description:[{
          required:true,message:'请输入产品的描述信息',trigger:'blur'
        }]
      }
    };
  },
  computed: {
    ...mapState("proCategory", ["proCategories"]),
  },
  methods: {
    ...mapActions("proCategory", ["findAllProductCategories"]),
    // 1.分页查询产品信息
    pageQueryProductions() {
            // 过滤查询参数，将空字符串的键值对删除掉
      for (let key in this.queryParams) {
        if (this.queryParams[key] == "") {
          delete this.queryParams[key];
        }
      }
      
     request.get("/product/pageQuery", {
          params: this.queryParams,
        })
        .then((res) => {
          this.tabelData = res.data;
        });
    },
    // 分页size-change事件
    handleSizeChange(pageSize) {
      // 点击分页容量，将最新的pageSize设置到数据模型中
      this.queryParams.pageSize = pageSize;
      // 重新调用分页查询的方法，做数据重载
      this.pageQueryProductions();
    },
    // 分页current-page-change事件
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.pageQueryProductions();
    },
    // 新增产品
    toAddProduct() {
      // 模态框打开之前，置空表单
      this.product = {};
      this.imageUrl = null;
      this.title = "新增产品";
      this.dialogVisible = true; // 打开模态框
    },
    // 上传插件成功的回调
    handleUploadSuccess(res, file) {
      // 将文件服务器响应的图片在线地址，设置到product
      this.product.photo = res;
      // 将成功上传的图片设置到预览标签上去
      this.imageUrl = res;
    },
    // 表单提交的确认按钮点击事件
    toSaveHandler() {
      // 表单校验   'proForm'为表名
      this.$refs["proForm"].validate((valid) => {
        if (valid) {
          // 用qs转换json为表单对象
          const data = qs.stringify(this.product);
          request.post("/product/saveOrUpdate", data).then((res) => {
            // 数据重载
            this.pageQueryProductions();
            // 关闭模态框
            this.dialogVisible = false;
            // 提示成功操作的信息
            this.$message.success(res.message);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 编辑按钮点击处理程序
    toEditHandler(row) {
      this.title = "修改产品信息";
      this.product = _.clone(row); // 将当前行数据显示深拷贝后，显示到表单里面去
      this.imageUrl = row.photo;
      this.dialogVisible = true; // 打开模态框
    },
    // 商品的上下架功能
    upDownProductHandler(id, e) {
      if (e.target.innerText == "上架") {
        this.$confirm("此操作将上架该产品, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          request
            .get("/product/online", {
              params: {
                id,
              },
            })
            .then((res) => {
              // 重载数据
              this.pageQueryProductions();
              // 提示成功操作的信息
              this.$message({
                message: res.message,
                type: "success",
              });
            });
        });
      } else {
        this.$confirm("此操作将下架该产品, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          request
            .get("/product/offline", {
              params: {
                id,
              },
            })
            .then((res) => {
              // 重载数据
              this.pageQueryProductions();
              // 提示成功操作的信息
              this.$message({
                message: res.message,
                type: "success",
              });
            });
        });
      }
    },
    // 添加按钮点击事件
    toAddHandler() {
      this.product={};
      this.imageUrl='';
      this.title = "新增产品";
      this.visible = true; // 打开模态框
    },
    // 上传插件成功的回调
    handleUploadSuccess(res, file) {
      // 将文件服务器响应的图片在线地址，设置到product
      this.product.photo = res;
      // 将成功上传的图片设置到预览标签上去
      this.imageUrl = res;
    },
    // 表单提交的确认按钮点击事件
    toSaveHandler() {
      const data = qs.stringify(this.product);
      request.post("/product/saveOrUpdate", data).then((res) => {
        // 数据重载
        this.pageQueryProductions();
        // 关闭模态框
        this.visible = false;
        // 提示成功操作的信息
        this.$message.success(res.message);
      });
    },
    // 编辑按钮点击处理程序
    toEditHandler(row) {
      this.title = "修改产品信息";
      this.product = _.clone(row); // 将当前行数据显示深拷贝后，显示到表单里面去
      this.imageUrl = row.photo;
      this.visible = true; // 打开模态框
    },
  },
  created() {
    this.pageQueryProductions(); // 调用分页查询产品信息
    this.findAllProductCategories(); // 调用查询所有产品栏目信息
  },
  watch:{
    'queryParams.status':{
         handler(newData,oldData){
          this.pageQueryProductions();
         },
         deep:true
    },
    'queryParams.productCategoryId':{
       handler(newData,oldData){
          this.pageQueryProductions();
       },
        deep:true
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/* 新增按钮样式 */
.toAddBtn {
  margin-right: 20px;
}
</style>
